package com.example.myimageshare.View;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.example.myimageshare.R;
import com.example.myimageshare.Utils.ImageUtil;
import com.example.myimageshare.View.PtotoView.PhotoViewPager;
import com.example.myimageshare.adapter.MyPhotoAdapter;
import com.example.myimageshare.domain.UserArt;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.graphics.PathUtils;
import androidx.viewpager.widget.ViewPager;

import android.os.Environment;
import android.os.FileUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PhotoViewActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String TAG = PhotoViewActivity.class.getSimpleName();
    private PhotoViewPager mViewPager;
    private int currentPosition;
    private int savePositon;
    private MyPhotoAdapter adapter;
    private TextView mTvImageCount;
    private TextView mTvSaveImage;
    private List<String> urls;

    private Toolbar toolbar = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo);
        initView();
        initData();
    }

    private void initView() {
        mViewPager = (PhotoViewPager) findViewById(R.id.view_pager_photo);
        mTvImageCount = (TextView) findViewById(R.id.tv_image_count);
        mTvSaveImage = (TextView) findViewById(R.id.tv_save_image_photo);
        mTvSaveImage.setOnClickListener(this);
        toolbar = findViewById(R.id.toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_keyboard_backspace_black_24dp);
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    }

    private void initData() {

        Intent intent = getIntent();
        Bundle userArtBundle = intent.getExtras();
        UserArt userArt = (UserArt) intent.getSerializableExtra("userArt");
        toolbar.setTitle("作品浏览");
        currentPosition = intent.getIntExtra("currentPosition", 0);
        Log.d(TAG, String.valueOf(currentPosition));
        urls = userArt.getUrls();

        adapter = new MyPhotoAdapter(urls, this);
        mViewPager.setAdapter(adapter);
        mViewPager.setCurrentItem(currentPosition, false);
        mTvImageCount.setText(currentPosition+ "/" + urls.size());
        mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                currentPosition = position;
                savePositon = position;
                Log.d(TAG+"cp:", String.valueOf(currentPosition));
                Log.d(TAG+"p", String.valueOf(position));
                mTvImageCount.setText(currentPosition + 1 + "/" + urls.size());
            }
        });
        intent.removeExtra("imgUri");
        intent.removeExtra("currentPosition");
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.tv_save_image_photo:
                saveImgToLocal(urls.get(savePositon));
                Log.d(TAG,"保存图片");
                break;
        }
    }


    private void saveImgToLocal(final String url) {

        Glide.with(this)
                .asBitmap()
                .load(url)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        saveImg(ImageUtil.getType(url),resource);
                        showToast("保存成功,相册可查看");
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
    }

    private void saveImg(String type, Bitmap bitmap) {
        //可访问的图片文件夹
        File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();
        //在图片文件夹下新建文件夹，保存图片
        String dirName = "MyImgSharePicture";
        File appDir = new File(file ,dirName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }

        //命名图片并保存
        String picName = System.currentTimeMillis() + "."+type;
        File currentFile = new File(appDir, picName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(currentFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG,
                    100 , fos);//质量为100表示设置压缩率为0,即原图
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 通知图库更新
        this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.fromFile(new File(currentFile.getPath()))));
    }


    private void showToast(String msg){
        Toast.makeText(PhotoViewActivity.this,msg,Toast.LENGTH_SHORT).show();
    }
}
